<?php

/**
 * Name: 安全隐患仓库层
 * User: Silent
 * Date: 2025-09-20
 * Time: 22:45:54
 */

namespace App\Repositories\Safety;

use App\Models\Safety\SafetyHazard;
use App\Repositories\BaseRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SafetyHazardRepository extends BaseRepository
{
    public function __construct(SafetyHazard $model)
    {
        parent::__construct($model);
    }

    /**
     *  列表.
     *
     * @param array $inputs
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list(array $inputs)
    {
        $query = $this->query()->where('employees_id', request('user_id'));
        if (!empty($inputs['searchText']) && !empty($inputs['searchType'])) {
            if ($inputs['searchType'] == 'id') {
                $query->where('id', $inputs['searchText']);
            } else {
                $query->where($inputs['searchType'], 'like', '%' . $inputs['searchText'] . '%');
            }
        }

        // 处理状态筛选
        if (!empty($inputs['processStatus'])) {
            $query->where('status', $inputs['processStatus']);
        }

        // 日期范围筛选
        if (!empty($inputs['startDate'])) {
            $query->whereDate('created_at', '>=', $inputs['startDate']);
        }
        if (!empty($inputs['endDate'])) {
            $query->whereDate('created_at', '<=', $inputs['endDate']);
        }

        // 分页
        $page     = $inputs['page']     ?? 1;
        $pageSize = $inputs['pageSize'] ?? 20;

        return $query->orderBy('id', 'desc')->paginate($pageSize, ['*'], 'page', $page);
    }

    /**
     * 添加安全隐患.
     *
     * @param array $inputs
     * @return array
     */
    public function addData(array $inputs): array
    {
        try {
            // 新增员工ID
            $inputs['employees_id'] = request('user_id');

            // 处理图片
            if (isset($inputs['cover_picture']) && is_array($inputs['cover_picture'])) {
                $inputs['cover_picture'] = implode(',', $inputs['cover_picture']);
            }

            $query = app(SafetyHazard::class)->create($inputs);

            return [
                'success' => true,
                'message' => '添加成功',
                'data'    => $query,
            ];
        } catch (\Exception $e) {
            Log::channel('hazard')->error('添加安全隐患失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '添加失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * 修改安全隐患.
     *
     * @param array $inputs
     * @return array
     */
    public function saveData(array $inputs): array
    {
        try {
            if (empty($inputs['id'])) {
                return [
                    'success' => false,
                    'message' => 'ID不能为空',
                ];
            }

            $id = $inputs['id'];
            unset($inputs['id']);

            // 检查记录是否存在
            $query = $this->detail($id);;
            if (!$query) {
                return [
                    'success' => false,
                    'message' => '安全隐患不存在',
                ];
            }

            // 处理图片
            if (isset($inputs['cover_picture']) && is_array($inputs['cover_picture'])) {
                $inputs['cover_picture'] = implode(',', $inputs['cover_picture']);
            }

            $updatedQuery = $query->update($inputs);

            return [
                'success' => true,
                'message' => '修改成功',
                'data'    => $updatedQuery,
            ];
        } catch (\Exception $e) {
            Log::channel('hazard')->error('修改安全隐患失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '修改失败: ' . $e->getMessage(),
            ];
        }
    }

    /**
     *  详情
     *
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function detail($id)
    {
        return $this->query()->where('employees_id', request('user_id'))->find($id);
    }

    /**
     *  删除.
     *
     * @param $query
     * @return array
     */
    public function destroy($query)
    {
        try {
            DB::transaction(function () use ($query) {
                $query->delete();
            });

            return [
                'success' => true,
                'message' => '删除成功',
            ];

        } catch (\Exception $e) {
            Log::channel('hazard')->error('删除安全隐患失败: ' . $e->getMessage());

            return [
                'success' => false,
                'message' => '删除失败: ' . $e->getMessage(),
            ];
        }
    }
}
